import 'package:dio/dio.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/page.dart';
import 'package:fate_blind_box/utils/picker.dart';
import 'package:flutter/material.dart';

import '../../../network/Api.dart';
import '../../../utils/bottom_sheet.dart';
import '../../../utils/provider.dart';

class PersonInformationTwoPage extends StatefulWidget {
  const PersonInformationTwoPage({Key? key}) : super(key: key);

  @override
  State<PersonInformationTwoPage> createState() => _PersonInformationTwoPageState();
}

class _PersonInformationTwoPageState extends State<PersonInformationTwoPage> {

  late BuildContext buildContext;
  var tall = '0';
  var weight = '0';
  var workAdress = '';
  var pcaList = [];
  var pcaOriginalList = [];
  var borthAdress = '';
  var marry = '';
  var child = '';
  var education = '';
  var identity = '';
  var money = '';
  var house = '';
  var car = '';
  var smokeOrBerr = '';


  var marryId = -1;
  var educationId = -1;
  var moneyId = -1;
  var houseId = -1;
  var carId = -1;
  var smokeOrBerrId = -1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _getPcaList();
  }

  @override
  Widget build(BuildContext context) {
    var _width = MediaQuery.of(context).size.width;
    var _height = MediaQuery.of(context).size.height;
    return Scaffold(
      appBar: AppBar(
        title: Column(
          children: [
            const Text(
              '完善信息2/2',
              style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                  color: Color(0xFF2C2C2C)
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 4),
              child: Image.asset(
                'images/person_progress_two2.png',
                width: 88,
                height: 4,
              ),
            )
          ],
        ),
        elevation: 0,
      ),
      backgroundColor: Colors.white,
      body: Builder(builder: (ctx){
        buildContext = ctx;
        return Container(
            width: _width,
            margin: const EdgeInsets.only(top: 10),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  _buildItem('images/person_tall.png', '身高', tall, '身高'),
                  _buildItem('images/person_weight.png', '体重', weight, '体重'),
                  _buildItem('images/person_workadress.png', '工作所在地', workAdress, '工作所在地'),
                  _buildItem('images/person_borthadress.png', '户籍所在地', borthAdress, '户籍所在地'),
                  _buildItem('images/person_marry.png', '婚姻状况', marry, '婚姻状况'),
                  _buildItem('images/person_child.png', '有无小孩', child,  '有无小孩'),
                  _buildItem('images/person_education.png', '学历', education, '学历'),
                  _buildItem('images/person_identity.png', '职业', identity, '职业'),
                  _buildItem('images/person_getmoney.png', '年收入', money, '年收入'),
                  _buildItem('images/person_house.png', '有无住房', house, '有无住房'),
                  _buildItem('images/person_car.png', '有无车', car, '有无车'),
                  _buildItem('images/person_smokeorberr.png', '抽烟喝酒', smokeOrBerr, '抽烟喝酒'),
                  GestureDetector(
                    onTap: () {
                      _submit();
                    },
                    child: Container(
                      height: 45,
                      margin: const EdgeInsets.fromLTRB(73, 37, 76, 0),
                      decoration: BoxDecoration(
                          color: const Color(0xFF7F69D9),
                          borderRadius: BorderRadius.circular(22.5)
                      ),
                      alignment: Alignment.center,
                      child: const Text("下一步", style: TextStyle(color: Colors.white, fontSize: 18),),
                    ),
                  ),
                  const SizedBox(height: 20,)
                ],
              ),
            )
        );
      })
    );
  }

  void _submit() {
    // if(!_verity()){
    //   return;
    // }
    Map<String, dynamic> param = {
      "id": Provider.memberId,
      "height": int.parse(tall.replaceAll('cm', '')),
      "weight": int.parse(weight.replaceAll('kg', '')),
      "homeAddr": workAdress,
      "domicilePlace": borthAdress,
      "maritalStatus": marryId,
      "edu": educationId,
      "occipation": identity,
      "incomeVal": moneyId,
      "purchase": houseId,
      "buyCar": carId,
      "aat":  smokeOrBerrId
    };
    loading(() async {
      final res = await Api.getInstance().modifyProfile(param);
      if (res['code'] == 0) {
        // Navigate.toPage(const PersonInformationThreePage());
        Navigate.toMain();
      } else {
        toast(res['msg']);
      }
    });
  }

  bool _verity() {
    if(tall.isEmpty){
      toast('请选择身高');
      return false;
    }
    if(weight.isEmpty){
      toast('请选择体重');
      return false;
    }
    if(workAdress.isEmpty){
      toast('请选择工作所在地');
      return false;
    }
    if(borthAdress.isEmpty){
      toast('请选择户籍所在地');
      return false;
    }
    if(marry.isEmpty){
      toast('请选择婚姻状况');
      return false;
    }
    if(child.isEmpty){
      toast('请选择有无小孩');
      return false;
    }
    if(education.isEmpty){
      toast('请选择学历');
      return false;
    }
    if(identity.isEmpty){
      toast('请选择职业');
      return false;
    }
    if(money.isEmpty){
      toast('请选择年收入');
      return false;
    }
    if(house.isEmpty){
      toast('请选择有无住房');
      return false;
    }
    if(car.isEmpty){
      toast('请选择有无车');
      return false;
    }
    if(smokeOrBerr.isEmpty){
      toast('请选择是否喝酒抽烟');
      return false;
    }
    return true;
  }

  Widget _buildItem(String icon, String title, String content, String id) {
    return GestureDetector(
      onTap: () {
        _onClick(id);
      },
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: 46),
        padding: const EdgeInsets.only(bottom: 5),
        alignment: Alignment.bottomCenter,
        height: 48,
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(
              width: 1,
              color: ThemeColor.dividerColor
            )
          )
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
              Row(
                children: [
                  Image.asset(
                    icon,
                    width: 16,
                    height: 16,
                  ),
                  const SizedBox(width: 6,),
                  Text(
                    title,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: Color(0xFF1B1F2F),
                    ),
                  ),
                ],
              ),
            Row(
                children: [
                  Text(
                    content.isEmpty ? '点击选择' : content,
                    style: TextStyle(
                      fontSize: 14,
                      color: content.isEmpty ? const Color(0xFF777777) : ThemeColor.appColor
                    ),
                  ),
                  const SizedBox(width: 8,),
                  Image.asset(
                    'images/person_threejiao.png',
                    width: 9,
                    height: 7,
                  ),
                ],
              )
            ],
        ),
      ),
    );
  }

  /// 获取省市县列表
  void _getPcaList() async {
    final Response<dynamic> res = await Api.getInstance().getPcaList();
    pcaOriginalList.addAll(res.data);
    for (var i in res.data) {
      final item = <String, dynamic>{};
      final cities = [];
      for (var c in i['children']) {
        final area = [];
        final city = <String, dynamic>{};
        for (var a in c['children']) {
          area.add(a['name']);
        }
        city[c['name']] = area;
        cities.add(city);
      }
      item[i['name']] = cities;
      pcaList.add(item);
    }
  }

  Future<void> _onClick(String id) async {
    switch(id) {
      case '身高':
        var list = <String>[];
        for(int i = 150; i <= 230; i++) {
          list.add('${i}cm');
        }
        showPickerWithDefaultPosition(buildContext, list, 20, (picker, selected) {
          print(picker.getSelectedValues()[0]);
          setState(() {
            tall = picker.getSelectedValues()[0].toString();
          });
        });
        break;
      case '体重':
        var list = <String>[];
        for(int i = 35; i <= 100; i++) {
          list.add('${i}kg');
        }
        showPickerWithDefaultPosition(buildContext, list, 20, (picker, selected) {
          setState(() {
            weight = picker.getSelectedValues()[0].toString();
          });
        });
        break;
      case '工作所在地':
        showPicker(buildContext, pcaList, (picker, selected) {
          String p = pcaOriginalList[selected[0]]['name'];
          String c = pcaOriginalList[selected[0]]['children'][selected[1]]['name'];
          String a = pcaOriginalList[selected[0]]['children'][selected[1]]['children'][selected[2]]['name'];
          setState(() {
            workAdress = '$p$c$a';
          });
        });
        break;
      case '户籍所在地':
        showPicker(buildContext, pcaList, (picker, selected) {
          String p = pcaOriginalList[selected[0]]['name'];
          String c = pcaOriginalList[selected[0]]['children'][selected[1]]['name'];
          String a = pcaOriginalList[selected[0]]['children'][selected[1]]['children'][selected[2]]['name'];
          setState(() {
            borthAdress = '$p$c$a';
          });
        });
        break;
      case '婚姻状况':
        showPicker(buildContext, ['未婚', '已婚', '再婚', '离异', '丧偶'], (picker, value) {
          setState(() {
            marry = picker.getSelectedValues()[0].toString();
            marryId = value[0];
          });
        });
        break;
      case '有无小孩':
        showPicker(buildContext, ['无', '1', '2', '3', '4', '5', '6'], (picker, value) {
          setState(() {
            child = picker.getSelectedValues()[0].toString();
          });
        });
        break;
      case '学历':
        showPicker(buildContext, ['小学', '初中', '高中', '大专', '本科', '硕士', '博士', '教授'], (picker, value) {
          setState(() {
            education = picker.getSelectedValues()[0].toString();
            educationId = value[0];
          });
        });
        break;
      case '职业':
        final value = await BottomSheetDialog.edit(context);
        if (value != null) {
          setState(() {
            identity = value;
          });
        }
        break;
      case '年收入':
        showPicker(buildContext, ['5万~10万', '10万~20万', '20万~50万', '50万~100万', '100万~300万', '300万以上'], (picker, value) {
          setState(() {
            money = picker.getSelectedValues()[0].toString();
            moneyId = value[0];
          });
        });
        break;
      case '有无住房':
        showPicker(buildContext, ['无', '有'], (picker, value) {
          setState(() {
            house = picker.getSelectedValues()[0].toString();
            houseId = value[0];
          });
        });
        break;
      case '有无车':
        showPicker(buildContext, ['无', '有'], (picker, value) {
          setState(() {
            car = picker.getSelectedValues()[0].toString();
            carId = value[0];
          });
        });
        break;
      case '抽烟喝酒':
        showPicker(buildContext, ['否', '抽烟', '喝酒', '抽烟也喝酒'], (picker, value) {
          setState(() {
            smokeOrBerr =  picker.getSelectedValues()[0].toString();
            smokeOrBerrId = value[0];
          });
        });
        break;
      default: break;
    }
  }
}
